package com.ihome.android.academy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager.LayoutParams;
import android.widget.CheckBox;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ihome.android.EAActivity;
import com.ihome.android.EAApp;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.market2.frag.RecommAppFragment;
import com.ihome.android.market2.frag.RecommAppFragmentEdu;
import com.ihome.android.market2.info.LayoutEdu;
import com.ihome.android.market2.info.TopTitleEdu;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.util.log.LogUtil;

public class MainActivity extends EAActivity{
	private String					TAG						= MainActivity.class.getSimpleName();

	private Context					mContext;
	@EAInjectView(id = R.id.hs_title)
	private HorizontalScrollView	hs_title;
	/** 一级导航栏 */
	@EAInjectView(id = R.id.ll_title)
	private LinearLayout			ll_title;
	@EAInjectView(id = R.id.rl_content)
	private RelativeLayout				rl_content;
	@EAInjectView(id = R.id.bg_main)
	private RelativeLayout bg_main;
	

	/** 一级标题，具体内容列表 */
	private List<TopTitleEdu>		mTopTitleEduList;
	private int						curPosition				= 0;
	private int						totalPage;

	private final int				MSG_CHANGE_POSITION		= 11;
	private Handler					mHandler;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_CHANGE_POSITION:
					int titlePos = (Integer) msg.obj;
					if (titlePos != curPosition) {
						titleSelected(titlePos);
					}
					break;
				default:
					break;
				}
			}
		};
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_edu);
		procHandler();
		mContext = MainActivity.this;
		bg_main.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(ConfigUtil.FILE_PATH+"bg.jpg")));
		initTitle();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		LogUtil.v(TAG, " -->  onKeyDown()----->curPosition= " +curPosition);

		if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN && ll_title.hasFocus()) {
			rl_content.requestFocus();
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction() == KeyEvent.ACTION_DOWN && rl_content.hasFocus()&&mAlbumAppListFragment.isAtTop()) {
			titleFocus();
//			titleSelected(curPosition);
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN && rl_content.hasFocus() && mAlbumAppListFragment.isAtRight() ) {
			return true;
		}

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			new DialogFactory(this).showDialog2Btn(getString(R.string.app_name), getString(R.string.app_exit_tip), getString(R.string.ok), getString(R.string.cancel_tip), new onBtnClickListener() {

				@Override
				public void btnLeftClickListener(View v) {

					MainActivity.this.finish();
				}

				@Override
				public void btnNeutralClickListener(View v) {

				}

				@Override
				public void btnRightClickListener(View v) {

				}

				@Override
				public void btnCloseClickListener(View v) {

				}

			}, true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void titleSelected(int position) {
		((CheckBox) ((LinearLayout) ll_title.getChildAt(position)).getChildAt(0)).setChecked(true);

		for (int i = 0; i < ll_title.getChildCount(); i++) {
			if (i != position) {
				((CheckBox) ((LinearLayout) ll_title.getChildAt(i)).getChildAt(0)).setChecked(false);
			}
		}
	}

	public void titleFocus() {
		if (ll_title != null)
			ll_title.getChildAt(curPosition).requestFocus();
	}

	private void initTitle() {
		hs_title.setVerticalScrollBarEnabled(false);
		int size = EAApp.getApp().mTopTitleEduList.size();
		mTopTitleEduList = new ArrayList<TopTitleEdu>();
		Comparator<TopTitleEdu> comparator = new Comparator<TopTitleEdu>() {
			public int compare(TopTitleEdu lhs, TopTitleEdu rhs) {
				Integer orderOne =  lhs.getSeat().getCol();
				Integer orderNext =  rhs.getSeat().getCol();
				return orderOne.compareTo(orderNext);
			}
		};
		
		Collections.sort(EAApp.getApp().mTopTitleEduList,comparator);
		
		for (int i = 0; i < size; i++) {
			TopTitleEdu info = new TopTitleEdu();
			info.setName(EAApp.getApp().mTopTitleEduList.get(i).getName());
			info.setUrl(EAApp.getApp().mTopTitleEduList.get(i).getUrl());
			info.setFlag(EAApp.getApp().mTopTitleEduList.get(i).getFlag());
			info.setSeat(EAApp.getApp().mTopTitleEduList.get(i).getSeat());
			mTopTitleEduList.add(info);
		}

		for (int i = 0; i < mTopTitleEduList.size(); i++) {
			TopTitleEdu info = mTopTitleEduList.get(i);
			info.setPosition(i);

			View mTitleItem = LayoutInflater.from(mContext).inflate(R.layout.title_item, null);
			mTitleItem.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));
			final CheckBox checkbox = (CheckBox) mTitleItem.findViewById(R.id.cb_item);
			
			checkbox.setText(info.getName());
//			checkbox.setRight(100);
//			checkbox.setPadding(info.getSeat().getCol()*10, 0, info.getSeat().getCol()*10, 0);
			checkbox.setTag(info);

			checkbox.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					LogUtil.v(TAG, " -->  onFocusChange()----->curPosition= " +curPosition);
					if (hasFocus) {
						TopTitleEdu infotv = (TopTitleEdu) v.getTag();
						mHandler.removeMessages(MSG_CHANGE_POSITION);
						mHandler.sendMessage(Message.obtain(mHandler, MSG_CHANGE_POSITION, infotv.getPosition()));
						titleFocus();
					}
				}
			});

			checkbox.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					TopTitleEdu infotv = (TopTitleEdu) v.getTag();
					LogUtil.v(TAG, " -->  onKey()----->curPosition= " +curPosition);
					if ((curPosition + 1) == mTopTitleEduList.size() && (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN)) {
						curPosition = 0;
						if(mAlbumAppListFragment.boolFlag()==1){
							initViewPage();
						}
						titleFocus();
						titleSelected(curPosition);
						return true;
					}
					
					if (curPosition == 0 && mTopTitleEduList.size() > 0 && (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN)) {
						curPosition = mTopTitleEduList.size() - 1;
//						if(mAlbumAppListFragment.boolFlag()==1){
//							initViewPage();
//						}
						titleFocus();
						titleSelected(curPosition);
						return true;
					}
					
					if(mTopTitleEduList.size() > 0&& (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN)){
						curPosition--;
						if(curPosition==0 &&mAlbumAppListFragment.boolFlag()==1){
							initViewPage();
						}
						titleFocus();
						titleSelected(curPosition);
						
						return true;
					}
					
					if(mTopTitleEduList.size() > 0&& (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN)){
						curPosition++;
//						if(mAlbumAppListFragment.boolFlag()==1){
//							initViewPage();
//						}
						titleFocus();
						titleSelected(curPosition);
						return true;
					}

					if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
						LogUtil.d(TAG, mTopTitleEduList.get(curPosition).getName());
						if(mTopTitleEduList.get(curPosition).getFlag()==0){
							if(!TextUtils.isEmpty(mTopTitleEduList.get(curPosition).getUrl()) ){
								Intent intent = new Intent();
								intent.putExtra(HttpKeys.KEY_FLAG,1);
								intent.putExtra(HttpKeys.KEY_APPURL,mTopTitleEduList.get(curPosition).getUrl());
								intent.setClass(MainActivity.this, WebViewActivity.class);
								startActivity(intent);
							}
						}else{
							initViewPage();
							titleFocus();
							titleSelected(curPosition);
						}
						

					}
					return false;
				}
			});

			ll_title.addView(mTitleItem);
		}

		titleSelected(0);
		
		titleFocus();
		initViewPage();

	}

	RecommAppFragmentEdu mAlbumAppListFragment;
	FragmentTransaction transaction1;
	private void initViewPage() {
		mAlbumAppListFragment = new RecommAppFragmentEdu();
		Bundle b = new Bundle();
		b.putString(HttpKeys.KEY_SECTIONID, mTopTitleEduList.get(curPosition).getName());
		b.putString(HttpKeys.KEY_SPECIALURL, mTopTitleEduList.get(curPosition).getUrl());
		b.putInt(HttpKeys.KEY_FLAG, mTopTitleEduList.get(curPosition).getFlag());
		b.putInt(HttpKeys.KEY_POSITION, curPosition);

		mAlbumAppListFragment.setArguments(b);
		transaction1 = getSupportFragmentManager().beginTransaction();
		transaction1.replace(R.id.rl_content, mAlbumAppListFragment);
		transaction1.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		transaction1.setTransitionStyle(R.style.Animations_PopDownMenu);
		transaction1.show(mAlbumAppListFragment);
		transaction1.commit();
	}

}
